package com.axjy.service.impl;

import com.axjy.mapper.MenuMapper;
import com.axjy.mapper.PermissionMapper;
import com.axjy.pojo.Menu;
import com.axjy.pojo.User;
import com.axjy.service.PermissionService;
import com.axjy.vo.TreeNode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("permissionService")
public class PermissionServiceImpl implements PermissionService{

    @Resource
   private MenuMapper menuMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public List<TreeNode> search4Tree(Integer rid) {
        List<Integer> menuIdList=permissionMapper.findMenuId(rid);
        List<TreeNode> list01=new ArrayList<TreeNode>();
        List<Menu> menuList01=menuMapper.findAllLevel01();
        for(Menu m01:menuList01){
            TreeNode node01=new TreeNode();
            node01.setId(m01.getId());
            node01.setText(m01.getName());
            if(menuIdList.contains(m01.getId())){
                node01.getState().setChecked(true);
            }
            List<Menu> menuList02= m01.getMenus();
            if(menuList02!=null&&menuList02.size()>0){
                List<TreeNode> list02=new ArrayList<TreeNode>();
                for(Menu m02:menuList02){
                    TreeNode node02=new TreeNode();
                    node02.setId(m02.getId());
                    node02.setText(m02.getName());
                    if(menuIdList.contains(m02.getId())){
                        node02.getState().setChecked(true);
                    }
                    list02.add(node02);
                }
                node01.setNodes(list02);
            }
            list01.add(node01);
        }
        return list01;
    }

    @Override
    public void grant(Integer rid, Integer[] mids) {
        permissionMapper.delAll(rid);
        if(mids!=null&&mids.length>0){
            for(Integer mid:mids){
                permissionMapper.add(rid,mid);
            }
        }
    }

    @Override
    public Map<Menu, List<Menu>> createNavigator(User loginUser) {
        Map<Menu, List<Menu>> map=new TreeMap<>();
       Integer roleId= loginUser.getRoleId();
       List<Integer> mids=permissionMapper.findMenuId(roleId);
      List<Menu> menus=menuMapper.findAllLevel01();
       if(mids!=null&&mids.size()>0){
           for(Integer mid:mids){
                Menu menu=menuMapper.findOne(mid);
                if(menu.getPId()==null){
                    List<Menu> level02=new ArrayList<Menu>();
                    map.put(menu,level02);
                    for(Integer mid2:mids){
                        Menu menu2=menuMapper.findOne(mid2);
                        if(menu2.getPId()!=null&&menu2.getPId().equals(menu.getId())){
                            level02.add(menu2);
                      }
                    }
                }
           }
       }
        return map;
    }
}
